package com.founder.bdyx.wxpro.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.founder.bdyx.wxpro.conf.WxConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import java.util.Date;

@Component
public class VerifyUtil {
    static Log log = LogFactory.getLog(VerifyUtil.class);

    @Autowired
    private WxConfig wxConfig;
    private static WxConfig configProperties;

    @PostConstruct
    public void init(){
        configProperties = this.wxConfig;
    }

    /**
     * http://39.99.137.160:8082/bat/home/loginToken
     *
     * 参数：
     * userId：用户id
     * index: 跳转地址 1-首页 2-发起申请 3-申请记录列表 4-申请详情页
     * salt：随机数
     * sign：userId+salt+secretKey，结果md5加密
     */
    public static String getLoginToken(String userId, String index){
        String applyUrl = configProperties.applyUrl;
        String salt = String.valueOf(System.currentTimeMillis());
        String sign = getSign(userId,salt);

        applyUrl = applyUrl.replace("USERID",userId)
                .replace("INDEX",index)
                .replace("SALT",salt)
                .replace("SIGN",sign);
        log.info("loginToken跳转页面：" + applyUrl);
        return applyUrl;
    }

    /**
     * 申请详情页，用于微信推送缴费通知跳转
     * http://39.99.137.160:8082/bat/home/loginToken
     *
     * 参数：
     * userId：用户id
     * index: 跳转地址 1-首页 2-发起申请 3-申请记录列表
     * salt：随机数
     * sign：userId+salt+secretKey，结果md5加密
     */
    public static String getApplyDetail(String userId, String index, String uuid){
        String applyDetailUrl = configProperties.applyDetailUrl;
        String salt = String.valueOf(System.currentTimeMillis());
        String sign = getSign(userId,salt);

        applyDetailUrl = applyDetailUrl.replace("USERID",userId)
                .replace("INDEX",index)
                .replace("SALT",salt)
                .replace("SIGN",sign)
                .replace("UUID",uuid);
        log.info("跳转申请详情页面：" + applyDetailUrl);
        return applyDetailUrl;
    }

    /*参数：
     uuid：待审核业务id，bat_custom_record表uuid字段
     exam：审核结果 0-不通过 1-通过
     rmk：不通过原因（可选）
     price：待支付金额
     salt：随机数
     sign：uuid+salt+secretKey，结果md5加密
     */
    public static JSONObject examRecord(JSONObject verifyInfo){
        String uuid = verifyInfo.getString("uuid");
        String singlePrice = verifyInfo.getString("singlePrice");
        String totalPrice = verifyInfo.getString("totalPrice");
        String transPrice = verifyInfo.getString("transPrice");
        String rmk = verifyInfo.getString("option");
        String status = verifyInfo.getString("verifyStatus");
        String extraPrice = verifyInfo.getString("extraPrice");

        if("pass".equals(status)){
            status = "1";
        }else {
            status = "0";
        }

        String salt = String.valueOf(System.currentTimeMillis());
        String sign = getSign(uuid, salt);

        JSONObject retObj = new JSONObject();
        retObj.put("salt",salt);
        retObj.put("sign",sign);
        retObj.put("uuid",uuid);
        retObj.put("exam",status);
        retObj.put("rmk",rmk);
        retObj.put("price",totalPrice);
        retObj.put("transPrice",transPrice);
        retObj.put("singlePrice",singlePrice);
        retObj.put("extraPrice",extraPrice);

        log.info("examRecord审核 入参：" + retObj);
        return retObj;
    }

    /**
     * 获取sign 的md5 串
     * @param paramKey
     * @param salt
     * @return
     */
    private static String getSign(String paramKey, String salt){
        String secretKey = configProperties.secretKey;
        String sign = paramKey + salt + secretKey;
        log.info("sign = " + sign);
        sign = DigestUtils.md5DigestAsHex(sign.getBytes());
        return sign;
    }

    /**
     * 获取微信交互access_token
     * @param servletContext
     * @return
     */
    public static String getAccessToken(ServletContext servletContext){
        String accessToken = (String) servletContext.getAttribute("access_token");
        if(accessToken!=null){
            Date currentDate = new Date();
            Date accessTokenTime = (Date) servletContext.getAttribute("access_token_time");
            int expiresIn = (int) servletContext.getAttribute("expires_in");
            if((int)(currentDate.getTime() - accessTokenTime.getTime())/1000 < expiresIn - 200){
                log.info("当前时间：" + currentDate.getTime());
                log.info("accessTime：" + accessTokenTime.getTime());
                log.info((currentDate.getTime() - accessTokenTime.getTime())/1000);
                return accessToken;
            }else {
                return requestToAccessToken(servletContext);
            }
        }else {
            return requestToAccessToken(servletContext);
        }
    }

    private static String requestToAccessToken(ServletContext servletContext){
        String appId = configProperties.appId;
        String appSecret = configProperties.appSecret;
        String url = configProperties.getAccessTokenUrl;
        url = url.replace("APPID",appId).replace("APPSECRET",appSecret);
        String ret = HttpUtil.sendGet(url);
        JSONObject json = JSON.parseObject(ret);
        String access_token = json.getString("access_token");
        int expires_in = json.getIntValue("expires_in");
        servletContext.setAttribute("access_token",access_token);
        servletContext.setAttribute("expires_in",expires_in);
        servletContext.setAttribute("access_token_time",new Date());
        log.info("刷新access_token:" + access_token);
        return access_token;
    }
}
